// cSpell:words hashbang gongju Cheng Jihua Kanban kechengjihua xiao
/* global $ page */

const pageClasses = {}

let lastPage = null

const pages = {}

exports.initRouter = function() {
    pageClasses["/"] = require("./index/IndexPage").IndexPage
    // pageClasses["/start-learn"] = require("./start-learn/StartLearn").StartLearn
    // pageClasses["/video-learn/:jhId/:kcId/:step"] = require("./video-learn/VideoLearn").VideoLearn

    // pageClasses["/lessons/:lessonId"] = require("./lesson-intro/LessonIntro").LessonIntro
    // pageClasses["/lessons/plan/:planId"] = require("./lesson-intro/LessonPlanIntro").LessonPlanIntro
    // pageClasses["/kb/:kechengjihuaId"] = require("./kechengjihua-kanban").KeChengJihuaKanban
    // pageClasses["/courseplan/:type"] = require("./courseplan/Courseplan").Courseplan

    // // 微实训
    // pageClasses["/practice/:jhId/:kcId/:step"] = require("./wei-shi-xun").WeiShiXun
    // // 小测验
    // pageClasses["/quiz/:jhId/:kcId/:step"] = require("./xiao-ce-yan").XiaoCeYan
    // // 报告页
    // pageClasses["/report/:answerId"] = require("./report/Report").Report
    pageClasses["*"] = require("./Page").NotFoundPage

    for (let path in pageClasses) {
        configRoute(path, pageClasses[path])
    }
    page.start({hashbang: true})
}

function configRoute(path, pageClass) {
    page(path, function(context) {
        if (path === "*") {
            if (context.path.indexOf("//") === 0) {
                const toPath = context.path.substring(1) // 保留最前面的一个斜线
                page.redirect(toPath)
                return
            } else if (context.path[0] !== "/") {
                const toPath = "/" + context.path // 必须最前面有一个斜线
                page.redirect(toPath)
                return
            }
        }

        const key = removeLeadingSlash(context.path)
        if (lastPage) {
            lastPage.close()

            if (lastPage._keep) {
                lastPage.$pageParent.hide()
            } else {
                delete pages[lastPage._key]
                lastPage.$pageParent.remove()
            }
        }

        if (pages[key]) {
            lastPage = pages[key]
            lastPage.open()
        } else {
            lastPage = newPage(key, pageClass, context)
        }
    })
}

function newPage(key, pageClass, context) {
    let $pageContainer = $(".page-container")

    let $pageParent = $("<div>", {class: "page-parent"})
        .appendTo($pageContainer)
    let thePage = new pageClass($pageParent, context)
    thePage._key = key

    pages[key] = thePage

    thePage.pLoadData().then(() => {
        const qBuild = thePage.pBuild()
        if (qBuild && qBuild.then)
            qBuild.then(() => {
                lastPage.open()
            })
        else
            lastPage.open()
    })

    return thePage
}

function removeLeadingSlash(path) {
    while (path[0] === "/") {
        path = path.substring(1)
    }
    return path
}
